package com.project.webservice.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.time.LocalDateTime;

public class JwtUtil {
    // 使用 Keys.secretKeyFor 方法生成符合 HS256 要求的密钥
    private static final byte[] SECRET_KEY_BYTES = Keys.secretKeyFor(SignatureAlgorithm.HS256).getEncoded();
    public static String getToken(String username, String password) {
        return Jwts.builder()
                .claim("username", username)
                .claim("password",password)
                .expiration(DateUtils.covertDate(LocalDateTime.now().plusHours(2)))
//                .claim("date", "2025-04-16")

                .signWith(SignatureAlgorithm.HS256, SECRET_KEY_BYTES)


                .compact();
    }


    public static String getToken(String username, String password,String searchDate) {
        return Jwts.builder()
                .claim("username", username)
                .claim("password",password)
                .claim("date", searchDate)
                .expiration(DateUtils.covertDate(LocalDateTime.now().plusHours(2)))


                .signWith(SignatureAlgorithm.HS256, SECRET_KEY_BYTES)


                .compact();
    }

    public static boolean checkToken(String token) {
        try {
            // 使用相同的密钥解析令牌
            Jwts.parser()
                    .setSigningKey(SECRET_KEY_BYTES)
                    .build()
                    .parseClaimsJws(token);

            // 如果没有抛出异常，说明令牌校验成功
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static void main(String[] args){
        String token = getToken("admin","123456");
        String token2 = getToken("test","999999");
        String token3 = getToken("guest","111111");
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(token);
        System.out.println(token2);
        System.out.println(token3);
        System.out.println(checkToken(token3));
//        System.out.println(checkToken("eyJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiIxMjM0NTYiLCJkYXRlIjoiMjAyNS0wNC0xNiJ9.NfF53pXNZ_JNEhE_qOfsOgthLjWPnd9RNhflinkUmPQ"));


    }
}

